<?php

namespace Api\Controller;

use Think\Controller;

class WeChatController extends Controller
{
    private $appid = 'wxdb881a1df61d1699';                 //微信公众号APPID
    private $appsecret = '85e271e9a7d9bcd5e4f3618585754ea7';//密匙
    private $url = 'http://mytest.bndvip.com/index.php?m=Api&c=WeChat&a=login';

    /**
     * 微信回调
     */
    public function notify()
    {
        // 导入微信支付sdk
        Vendor('Weixinpay.Weixinpay');
        $wxpay = new \Weixinpay();
        $result = $wxpay->notify();
        if ($result) {
            // 验证成功 修改数据库的订单状态等
            $order_no = $result['out_trade_no'];
            //查询订单是否存在
            $order_result = M("dishes_order")->where("order_no='$order_no'")->find();
            if ($order_result) {
                //改变订单支付状态
                M()->startTrans();
                $data['order_state'] = 2;
                $data['pay_time'] = time();
                $update_result = M('order')->where("order_no='$order_no'")->save($data);
                //改变菜品的库存
                $dishes = M('order_detail')->where("order_id='$order_no'")->select();
                if ($dishes) {
                    foreach ($dishes as $v) {
                        $dish[] = $v['dish_id'];
                    }
                    $dishId = implode(',', $dish);
                    $where['id'] = array('in', $dishId);
                    //查询菜品的信息
                    $dishInfo = M('dishes')->where($where)->select();
                    foreach ($dishInfo as $k => $va) {
                        $dishTmp[$k]['id'] = $va['id'];
                        $dishTmp[$k]['num'] = $va['num'];
                        $dishTmp[$k]['sales'] = $va['sales'];
                    }
                    $list = array();
                    foreach ($dishes as $k => $v) {//销售掉的
                        foreach ($dishTmp as $value) {//原来的
                            if ($v['dish_id'] == $value['id']) {
                                $countTmp = $value['num'] - $v['count'];
                                $salesTmp = $value['sales'] + $v['count'];
                                if ($countTmp < 0) {
                                    $countTmp = 0;
                                }
                                $list[$k] = array('dish_id' => $value['id'], "num" => $countTmp, "sales" => $salesTmp);
                            }
                        }
                    }
                    $update_dish = M()->saveAll($list, 'dishes');
                    if ($update_dish && $update_result) {
                        M()->commit();
                    } else {
                        M()->rollback();
                    }
                } else {
                    error_log("菜品不存在", 3, 'err_log.txt');
                }
            } else {
                error_log("订单不存在", 3, 'err_log.txt');
            }
        } else {
            error_log("aaa", 3, 'err_log.txt');
        }

    }

    /**
     * 微信登陆开始
     */
    public function start()
    {
        $store_id = I('get.store_id');
        $_SESSION['STORE_ID'] = $store_id;
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this->appid . '&redirect_uri=' . urlencode($this->url) . '&response_type=code&scope=snsapi_userinfo&state=state#wechat_redirect';
        header('location:' . $url);
        exit();
    }

    /**
     * 登录
     */
    public function login()
    {
        $store_id = $_SESSION['STORE_ID']; //店铺id
        $code = $_GET['code'];
        $access_token = $this->getUserAccessToken($code); //获取授权token
        $UserInfo = $this->getUserInfo($access_token); //获取用户信息
        $openid = $UserInfo['openid'];
        $data['open_id'] = $openid;
        $nickname = json_encode($UserInfo['nickname']);
        $nickname = preg_replace("#(\\\ue[0-9a-f]{3})#ie", "addslashes('\\1')", $nickname);
        $nickname = json_decode($nickname);

        $data['nickname'] = $nickname;
        $data['headimgurl'] = $UserInfo['headimgurl'];
        $data['sex'] = $UserInfo['sex'];
        $data['time'] = time();

        $user_info = M('user')->where(['open_id' => $openid])->find();
//        dump($user_info);die;
        if ($user_info) {
            if ($store_id == $user_info['store_id']) {
//                echo '已登录过';die;
                //已经登陆过
                $customer_id = $user_info['customer_id'];
                $_SESSION['customer_id'] = $customer_id;
                M('user')->where(["customer_id" => $customer_id])->save($data);
                redirect('index.php/Home/Index/index');
            } else {
//                echo '未登录过';die;
                //未登陆过(在新的店铺注入)
                if ($openid) {
                    $randNum = $this->getRandString(6);
                    $data['customer_id'] = date('YmdHis') . $randNum;
                    $_SESSION['customer_id'] = $data['customer_id'];
                    $data['store_id'] = $store_id;
                    M('user')->add($data);
                    redirect('index.php/Home/Index/index');
                }
            }
        } else {
//            echo '第一次登陆';die;
            //未登陆过(首次注入店铺)
            if ($openid) {
                $randNum = $this->getRandString(6);
                $data['customer_id'] = date('YmdHis') . $randNum;
                $_SESSION['customer_id'] = $data['customer_id'];
                $data['store_id'] = $store_id;
                M('user')->add($data);
               redirect('index.php/Home/Index/index');
            }
        }
    }

    /**
     * 获取授权token
     * @param $code
     * @return bool|string
     */
    private function getUserAccessToken($code)
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$this->appid&secret=$this->appsecret&code=$code&grant_type=authorization_code";
        $res = file_get_contents($url);
        return json_decode($res);
    }

    /**
     * 获取用户信息
     * @param $accessToken
     * @return mixed
     */
    private function getUserInfo($accessToken)
    {
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$accessToken->access_token&openid=$accessToken->openid&lang=zh_CN";
        $UserInfo = file_get_contents($url);
        return json_decode($UserInfo, true);
    }

    /**
     * 此AccessToken   与 getUserAccessToken不一样
     * 获得AccessToken
     * @return mixed
     */
    private function getAccessToken()
    {
        // 获取缓存
        $access = cache('access_token');
        // 缓存不存在-重新创建
        if (empty($access)) {
            // 获取 access token
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this -> appid}&secret={$this->appsecret}";
            $accessToken = file_get_contents($url);

            $accessToken = json_decode($accessToken);
            // 保存至缓存
            $access = $accessToken->access_token;
            cache('access_token', $access, 7000);
        }
        return $access;
    }

    /**
     * 获取JS证明
     * @param $accessToken
     * @return mixed
     */
    private function _getJsapiTicket($accessToken)
    {

        // 获取缓存
        $ticket = cache('jsapi_ticket');
        // 缓存不存在-重新创建
        if (empty($ticket)) {
            // 获取js_ticket
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . $accessToken . "&type=jsapi";
            $jsTicket = file_get_contents($url);
            $jsTicket = json_decode($jsTicket);
            // 保存至缓存
            $ticket = $jsTicket->ticket;
            cache('jsapi_ticket', $ticket, 7000);
        }
        return $ticket;
    }

    /**
     * 获取JS-SDK调用权限
     */
    public function shareAPi(Request $request)
    {
        header("Access-Control-Allow-Origin:*");
        // 获取accesstoken
        $accessToken = $this->getAccessToken();
        // 获取jsapi_ticket
        $jsapiTicket = $this->_getJsapiTicket($accessToken);

        // -------- 生成签名 --------
        $wxConf = array('jsapi_ticket' => $jsapiTicket,
            'noncestr' => md5(time() . '!@#$%^&*()_+'),
            'timestamp' => time(),
            'url' => $request->post('url'));  //这个就是你要自定义分享页面的Url啦  );


        $string1 = sprintf('jsapi_ticket=%s&noncestr=%s×tamp=%s&url=%s', $wxConf['jsapi_ticket'], $wxConf['noncestr'], $wxConf['timestamp'], $wxConf['url']);
        // 计算签名
        $wxConf['signature'] = sha1($string1);
        $wxConf['appid'] = $this->appid;
        return json($wxConf);
    }
}